import React, { useEffect, useRef } from 'react';
import { LrcLine } from '../utils/lrcParser';
import './LrcDisplay.css';

interface LrcDisplayProps {
  lrcLines: LrcLine[];
  currentIndex: number;
  onLineClick?: (index: number) => void;
}

const LrcDisplay: React.FC<LrcDisplayProps> = ({ 
  lrcLines, 
  currentIndex, 
  onLineClick 
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const currentLineRef = useRef<HTMLDivElement>(null);

  // 自动滚动到当前歌词
  useEffect(() => {
    if (currentLineRef.current && containerRef.current) {
      const container = containerRef.current;
      const currentLine = currentLineRef.current;
      
      const containerHeight = container.clientHeight;
      const lineTop = currentLine.offsetTop;
      const lineHeight = currentLine.clientHeight;
      
      // 计算滚动位置，让当前行显示在容器中央
      const scrollTop = lineTop - containerHeight / 2 + lineHeight / 2;
      
      container.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      });
    }
  }, [currentIndex]);

  if (lrcLines.length === 0) {
    return (
      <div className="lrc-display">
        <div className="lrc-empty">
          <p>暂无歌词</p>
        </div>
      </div>
    );
  }

  return (
    <div className="lrc-display" ref={containerRef}>
      <div className="lrc-content">
        {lrcLines.map((line, index) => (
          <div
            key={index}
            ref={index === currentIndex ? currentLineRef : null}
            className={`lrc-line ${index === currentIndex ? 'active' : ''} ${
              index < currentIndex ? 'passed' : ''
            }`}
            onClick={() => onLineClick?.(index)}
          >
            <span className="lrc-time">{line.originalTime}</span>
            <span className="lrc-text">{line.text}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default LrcDisplay;